import { reqUserInfo } from '@/utils/api'
import router from '../router'

const state = {
  userInfo: localStorage.getItem('userInfo') || {},
  token: localStorage.getItem('token') || '',
  nickName: localStorage.getItem('nickName') || '',
}

const mutations = {
  // 获取用户信息
  GETUSERINFO(state, data) {
    state.userInfo = data
  },
  // 获取token
  GETTOKEN(state, token) {
    state.token = token
  },
  // 获取用户姓名
  GETNICKNAME(state, name) {
    state.nickName = name
  },
  // 移除用户信息
  REMOVEUSERINFO(state) {
    state.userInfo = {}
  },
  // 移除token
  REMOVETOKEN(state) {
    state.token = ''
  },
  // 移除用户姓名
  REMOVENCIKNAME(state) {
    state.nickName = ''
  }
}

const actions = {
  // async getUserInfo({commit}) {
  //   let result = await reqUserInfo()
  //   if(result.code == 200) return commit("GETUSERINFO", result.data)
  // }
  getUserInfo({ commit }) {
    // 判断用户是否登录
    if(!localStorage.getItem("token")) {
      if(confirm("未登录,是否去登录")) {
        router.push("/login")
      }
      return 
    } 
    //  针对后台总是过一段时间就登录失效的解决
    reqUserInfo().then((res) => {
      if (res.code == 200) {
        // 将数据存储在本地保持持久化
        localStorage.setItem("userInfo", res.data)
      } else if (res.code == 208) {
        // 移除本地缓存
        localStorage.removeItem("token");
        localStorage.removeItem("nickName")
        localStorage.removeItem("userInfo")
        // 改变仓库中的值
        commit("REMOVETOKEN");
        commit("REMOVENCIKNAME");
        commit("REMOVEUSERINFO");
        if (confirm("登录信息失效，是否重新登录")) {
          router.push('/login');
        } else {
          router.back()
        }
      }
    }, (error) => {
      return Promise.reject(new Error(error.message))
    })
  }
}

export default {
  state,
  mutations,
  actions
}